<?php

namespace app\middleware;
use think\Response;
use think\facade\Db;

class Auth
{
    // 白名单
    protected static $whiteList = ['/index/login','/WechatMiniProgram/getUnlimitedQrCode','/WechatMiniProgram/checkQrCodeCache','/WechatMiniProgram/getAccessToken','/WechatMiniProgram/clearQrCodeCache','/WechatMiniProgram/setOpenidCache','/WechatMiniProgram/loginByOpenid','/WechatMiniProgram/checkCompanyCode','/WechatMiniProgram/registerUser','/WechatMiniProgram/checkUserName','/WechatMiniProgram/bindUser','/AssetList/getAssetByAssetCode'];

    public function handle($request, \Closure $next)
    {
        
        // 过滤白名单
        $baseUrl = $request->baseUrl();
//        var_dump(self::$whiteList);
//        var_dump($baseUrl);
        if (in_array($baseUrl,self::$whiteList)){
            return $next($request);
        }
        // 如果不在白名单中，进行身份验证逻辑（这里仅为示例，需要替换为实际验证逻辑）
         $auth=$request->header('Authorization');
         $checkAuth=checkToken($auth);

         //判断是否重复登陆,取出数据库中的user_sessionID和$checkAuth中的user_sessionID是否一致

//        var_dump($checkAuth);
        $user_sessionID=Db::name('user')->where('user_id',$checkAuth['data']->user->user_id)->where('user_sessionID',$checkAuth['data']->user->user_sessionID)->find();


        if(!$user_sessionID){

            return json(['code' => 401, 'msg' => '请勿重复登陆']);
        }


        if($checkAuth['code']== 1)
        {
            
             //按钮级权限验证
            if(!ButtonAuth($baseUrl,$checkAuth['data']->user->user_company_id,$checkAuth['data']->user->user_id))
            {
                return json(['code' => 402, 'msg' => '权限不足']);
            }

            //var_dump($baseUrl);

            $request->auth=$checkAuth;
            return $next($request);

        }else{

            return json(['code' => 401, 'msg' => $checkAuth['msg']]);
        }



    }
}